package com.xyzh05.webapp.action;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import com.xyzh05.Constants;
import com.xyzh05.model.Department;
import com.xyzh05.model.Role;
import com.xyzh05.model.User;
import com.xyzh05.model.UserInfo;
import com.xyzh05.service.DictItemManager;
import com.xyzh05.service.UserExistsException;
import com.xyzh05.service.UserInfoManager;

/**
 * Action to allow new users to sign up.
 */
public class SignupAction extends BaseAction {
    private static final long serialVersionUID = 6558317334878272308L;
    private UserInfoManager userInfoManager;
    private DictItemManager dictItemManager;
    private User user;
    private Role role;
    private UserInfo userInfo;
    private Department department;
    private String username;
    private String repeatPassword;
    private String cancel;
    private Integer actionType;
    private Boolean auditStatus = false;
    

    public Integer getActionType() {
		return actionType;
	}

	public void setActionType(Integer actionType) {
		this.actionType = actionType;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public DictItemManager getDictItemManager() {
		return dictItemManager;
	}

	public void setDictItemManager(DictItemManager dictItemManager) {
		this.dictItemManager = dictItemManager;
	}

	public UserInfoManager getUserInfoManager() {
		return userInfoManager;
	}

	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public String getCancel() {
		return cancel;
	}

	public void setCancel(String cancel) {
        this.cancel = cancel;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getRepeatPassword() {
		return repeatPassword;
	}

	public void setRepeatPassword(String repeatPassword) {
		this.repeatPassword = repeatPassword;
	}

	public Boolean getAuditStatus() {
		return auditStatus;
	}

	public void setAuditStatus(Boolean auditStatus) {
		this.auditStatus = auditStatus;
	}

	/**
     * When method=GET, "input" is returned. Otherwise, "success" is returned.
     * @return cancel, input or success
     */
    public String execute() {
        return SUCCESS;
    }

    /**
     *初始化登录 
     */
    public String mainMenu(){
		try {
			user = getCurrentUser();
			auditStatus = user.getUserDepartment().getStatus() == Department.DEFAULT_STATUS;
		} catch (Exception e) {
			return INPUT;
		}
    	return SUCCESS;
    }
    
    /**
     * Returns "input"
     * @return "input" by default
     */
    public String doDefault() {
        return INPUT;
    }

    /**
     * Save the user, encrypting their passwords if necessary
     * @return success when good things happen
     * @throws Exception when bad things happen
     */
    public String save() throws Exception {
    	// Set the default user role on this new user
    	if(actionType != null && actionType == 1){
    		department = new Department();
    		department.setDictItemByDeptTypeId(dictItemManager.get(Department.DEPARTMENT));
    		department.setDisplayName(user.getDisplayName());
    		department.setAddress(userInfo.getDeptAddress());
    		
    		try {
    			department = departmentManager.save(department);				
			} catch (Exception e) {
				return INPUT;
			}
    		role = new Role();
    		role.setName(Role.ROLE_COMPANY);
    		role.setRoleType(dictItemManager.get(Role.DEFAULT_ROLE_COMPANY));
    		role.setDepartment(department);
			
    		try {
    			role = roleManager.save(role);				
			} catch (Exception e) {
				return INPUT;
			}
    		
    		user.setRoleId(role.getId());
    		user.addRole(role);
    		
    		userInfo.setDeptName(user.getDisplayName());
    	}else{
    		user.addRole(roleManager.get(Role.DEFAULT_ROLE_USER));    		
    	}
    	
		user.setEmail(user.getUsername());
		user.setUserInfo(userInfo);
		userInfo.setUser(user);
		
		try {
            user = userManager.saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity 
            log.warn(ade.getMessage());
            getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
            return null; 
        } catch (UserExistsException e) {
            log.warn(e.getMessage());
            List<Object> args = new ArrayList<Object>();
            args.add(user.getUsername());
            args.add(user.getEmail());
            addActionError(getText("errors.existing.user", args));

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            return INPUT;
        }

        saveMessage(getText("user.registered"));
        getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

        // log user in automatically
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
        auth.setDetails(user);
        SecurityContextHolder.getContext().setAuthentication(auth);
    	
        /**
        // Send an account information e-mail
        mailMessage.setSubject(getText("signup.email.subject"));

        try {
            sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
        } catch (MailException me) {
            addActionError(me.getMostSpecificCause().getMessage());
        }*/
        return SUCCESS;
    }
}
